import * as types from "./mutation-types";
import Api from "api/api";

const state = {
  questionList: {},
  currentQuestion: {},
  keys: ["A", "B", "C", "D", "E", "F", "G", "H"],
  searchQuestionCondition: {
    pageSize: 10,
    title: "",
    type: "",
    classIds: ""
  }
};

const getters = {
  keys: state => state.keys,
  questionList: state => state.questionList,
  currentQuestion: state => state.currentQuestion,
  searchQuestionCondition: state => state.searchQuestionCondition
};

const actions = {
  getQuestionPageS({ commit }, param) {
    return Api.getQuestionPage(param).then(ret => {
      commit(types.UPDATE_QUESTION_LIST, ret.data.data);
      return ret;
    });
  },
  getQuestionS({ commit }, id) {
    return Api.getQuestion({ id: id }).then(ret => {
      var payload = ret.data.data;
      var opts = { opts: [] };
      payload = Object.assign(payload, opts);
      var tem = payload.options.split("\n");
      console.log(tem);
      var ans = payload.answer.split("、");
      if (tem) {
        tem.map((item, index) => {
          var chek = false;
          ans.map((s, d) => {
            if (s === state.keys[index]) {
              chek = true;
            }
          });
          payload.opts.push({
            value: item.substring(2, item.length),
            checked: chek,
            key: state.keys[index]
          });
        });
      }
      commit(types.UPDATE_CURRENT_QUESTION, payload);
      return ret;
    });
  },
  addOrUpdateQuestionS({ commit }, payload) {
    return Api.addOrUpdateQuestion({ body: payload }).then(ret => {
      return ret;
    });
  },
  importQuestionS({ commit }, payload) {
    return Api.importQuestion(payload).then(ret => {
      return ret;
    });
  },
  deleteQuestionS({ commit }, param) {
    return Api.deleteQuestion(param).then(ret => {
      return ret;
    });
  }
};
const mutations = {
  [types.UPDATE_QUESTION_LIST](state, payload) {
    state.questionList = payload;
  },
  [types.INIT_CURRENT_QUESTION](state, payload) {
    state.currentQuestion = {
      title: "",
      options: "",
      opts: [
        {
          value: "",
          checked: false,
          key: "A"
        }
      ],
      answer: "",
      type: "zks",
      analysis: "",
      score: 1,
      clazzs: [
        {
          id: 0,
          clazz: ""
        }
      ]
    };
  },
  [types.UPDATE_CURRENT_QUESTION](state, payload) {
    state.currentQuestion = payload;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};
